//
//  Component.swift
//  MacDemo
//
//  Created by FH on 2020/12/2.
//  Copyright © 2020 FH. All rights reserved.
//

import Foundation


// TODO: remove

protocol ComponentTemplate {
    func getView() -> FLView
    func layout(_ layoutContext: FLContext, _ superView: FLView)
}

class Component {
    private let localStates: StatesStore = StatesStore()
    private let layoutContext: FLContext!
    private var children: [Component] = []
    
    init(layoutContext: FLContext?=nil) {
        self.layoutContext = layoutContext
//        self.bindStates()
    }
    
    func getTemplate() -> ComponentTemplate? {
        return nil
    }
    
    func needUpdate() -> Bool {
        return false
    }
    
    func dataBinding() {
        
    }
    
    final func add(child: Component) {
        self.children.append(child)
    }
    
    @discardableResult
    final func render(_ superView: FLView?=nil, _ props: [String : Any]=[:]) -> Bool {
        if needUpdate() {
            if let template = self.getTemplate() {
                localStates.appendStates(states: props, sectionName: "")
                if let layoutContext = self.layoutContext, let superView = superView {
                    template.layout(layoutContext, superView)
                    self.dataBinding()
                }
            }
            
            if self.children.count > 0 {
                let currView = self.getTemplate()?.getView()
                for child in children {
                    // TODO: .appendStates()分离，供needUpdate()、render()使用
                    if child.needUpdate() {
                        child.render(currView, localStates.toDictionary())
                    }
                }
            }
            return true
        }
        return false
    }
    
    final func toDictionary() -> [String : Any] {
        return self.localStates.toDictionary()
    }
}
